<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
        <el-form :model="queryForm"  ref="queryRef">
            <el-row :gutter="24">
                <el-col :span="8" class="mb20">
                    <el-form-item label="姓名" prop="personName">
                        <el-select v-model="queryForm.personName" filterable  style="width: 240px" clearable>
                            <el-option v-for="item in options"  :key="item.personName" :label="item.personName" :value="item.personName"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6" class="mb20">
                    <el-form-item>
                        <el-button icon="search" type="primary" @click="queryList">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                        <el-button @click="goBack">返回</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="gridData" @selection-change="handleCurrentChange"  ref="tableRef">
            <el-table-column type="selection" width="55" />
            <el-table-column property="personName" label="姓名"/>
            <el-table-column property="groupName" label="参与组织"/>
            <el-table-column property="postName" label="参与岗位"/>
            <el-table-column property="useTime" label="考试用时"/>
            <el-table-column property="automaticScore" label="自动判卷成绩(分)" :formatter="formatScore"/>
            <el-table-column property="manualScore" label="人工判卷成绩(分)" :formatter="formatScore"/>
            <el-table-column property="totalScore" label="总成绩(分)" :formatter="formatScore"/>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button icon="edit-pen" text type="primary" @click="getGrade(scope.row)">人工判卷</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="avue-crud__pagination">
            <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
        </div>
    </div>
      <!-- 人工判卷弹框  -->
      <el-dialog v-model="centerDialogVisible1"  width="60%" >
          <template #header>
        <span class="dialog-header">
           <el-text style="font-size:20px;font-weight: bold;margin-left: 20px">人工判卷</el-text>
          <el-text style="font-size:20px;font-weight: bold;color: red">(只允许进行一次打分，请谨慎评分！)</el-text>
        </span>
          </template>
          <div class="line"></div>
          <el-row style="margin-top: 10px">
                  <div v-for="(item, index) in ManualDataList" :key="item.id" class="item scroll">
                      <el-card>
                          <el-row>
                              <span style="font-weight: bold;font-size: 16px;margin-right: 20px;margin-bottom: 5px">第{{ index + 1 }}道</span>
                              <span style="margin-right: 20px">总分: {{ item.totalScore }}分</span>
                              <span>得分: </span>
                              <el-input-number v-model.number="item.getScore" size="small" :min="0" :disabled="manualNumber" :max=item.totalScore @change="handleChange($event, index)" style="width: 90px"/>
                              <span>分</span>
                          </el-row>
                          <el-row style="margin-bottom: 5px">
                              <span>题目:{{item.question}}</span>
                          </el-row>
                          <el-row style="margin-bottom: 5px">
                              <span>解析:{{item.correctValue}}</span>
                          </el-row>
                          <el-row style="margin-bottom: 30px">
                              <span>答案:{{item.userValue}}</span>
                          </el-row>
                      </el-card>
                  </div>
          </el-row>
          <template #footer>
              <span style="margin-right: 100px;font-size: 18px;">人工判卷总分:{{totalScoreList }}分</span>
              <span class="dialog-footer">
                <el-button type="primary" style="margin-left: -10px;margin-top: -10px" @click="submitBtn1">确认</el-button>
              </span>
          </template>
      </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemXxrwTranscript">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { gradenameList,editListst,markexampapersList,submitList} from "/@/api/train/xxrwTranscript";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import { useRoute, useRouter } from 'vue-router';
import { reactive, ref, watch } from 'vue';
import { getManualData } from '/@/api/train/ksglTranscript';

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典
const queryForm = reactive({
	personName:''
})
const getXxrwScoreList = ref([])
const objManual1 = ref({})
const objManual = ref({})
// 定义变量内容
const formDialogRef = ref()
const route = useRoute();
const gridData = ref<any[]>([]); // 根据你的数据结构来定义类型
const totalPage = ref(0);
const pageIndex = ref(1); // 假设第一页是1
const pageSize = ref(10); // 假设每页显示10条数据
const totalScoreList = ref(0)
const ManualDataList = reactive([{}])
// 人工判卷
const manualNumber = ref(false)
// 定义查询字典
const options =reactive([{
	personName: '',
}])
const items = ref<any[]>([]);
// 搜索变量
const ExamAndDataDto = reactive({
	examId:''
})
const ManualDataDto = reactive({
	examId:'',
	userName:''
})
const showSearch = ref(true)
const queryRef = ref()
const centerDialogVisible1 = ref(false)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
onMounted(()=> {
	deptTreeList()
	namedataList()
})
const router = useRouter();
//返回上一页
const goBack = () => {
	router.push('/train/xxrwTaskList/index');
};
// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields()
	deptTreeList()
}
// 保留整数
const formatScore =(row:any, column:any, cellValue:any)=> {
	// 首先尝试将 cellValue 转换为数字
	const value = Number(cellValue);
	// 检查转换后的值是否为数字且不是 NaN
	if (!isNaN(value)) {
		// 如果是整数，直接返回
		if (Number.isInteger(value)) {
			return value;
		} else {
			// 保留一位小数并返回字符串形式
			return value.toFixed(0);
		}
	} else {
		// 如果转换失败，可以返回一个默认值或者处理错误情况
		console.error('无法将 cellValue 转换为数字:', cellValue);
		return ''; // 或者返回其他合适的默认值
	}
}
// 获取姓名
const namedataList = async ()=> {
	console.log(route.query,'444444444')
	ExamAndDataDto.examId = route.query.examId
	// console.log(ExamAndDataDto.examId,'examId名字');
	// console.log('examId123',ExamAndDataDto.examId);
	gradenameList(ExamAndDataDto).then((res) => {
	console.log(res,'res名字');
	options.length = 0;
	for (let index = 0; index < res.data.length; index++) {
		options.push({
			personName: res.data[index].personName,
		});
	}
	console.log("查询分类121===>",options);
});
}
// 成绩单
const deptTreeList = async () => {
	console.log(route.query,'444444444')
	const examId = route.query.examId
	console.log('examId123',examId);
	try {
		const response = await editListst({
			examId:examId,
			current: pageIndex.value,
			size: pageSize.value
		});
		// console.log(response, '关联资料');
		gridData.value = response.data.records
        totalPage.value = response.data.total;
	}catch (error) {
		console.error('Error fetching data:', error);
	}
};
// 每页数
const  sizeChangeHandle = (val:number)=> {
	pageSize.value = val
	pageIndex.value = 1
	deptTreeList()
}
// 当前页
const  currentChangeHandle =(val:number)=> {
	pageIndex.value = val
	deptTreeList()
}
// 查询
const queryList = async () => {
	queryForm.examId = route.query.examId
	console.log(queryForm.personName,'queryForm.personName');
	editListst(queryForm).then((res) => {
        gridData.value = res.data.records
        totalPage.value = res.data.total;
		console.log(res,'res');
	})
}
const handleChange = (val:any,index:any) =>{
	ManualDataList[index].getScore = val
	calculateTotalScore()
	console.log('totalScoreList.value',totalScoreList.value)
}
const calculateTotalScore=() =>{
	totalScoreList.value = ManualDataList.reduce((total, item) => total + item.getScore, 0);
}
// 人工判卷
const getGrade = (row:any) =>{
  manualNumber.value = row.manualNumber
	ManualDataList.length = 0
	centerDialogVisible1.value = true
	objManual.value= {
		examId :route.query.examId,
		userName:row.userName
	}
	console.log(objManual.value,'打印值');
	markexampapersList(objManual.value).then(res=>{
		Object.assign(ManualDataList,res.data)
        calculateTotalScore()
	})
}
// 提交人工判卷
const submitBtn1 = async () =>{
	centerDialogVisible1.value = false
	ManualDataList.forEach(item=>{
		let obj ={
			getScore:item.getScore,
			id:item.id
		}
		getXxrwScoreList.value.push(obj)
		console.log(getXxrwScoreList,getXxrwScoreList.value,'getXxrwScoreList');
	})
	objManual1.value = objManual.value
	objManual1.value.taskId = route.query.taskId
	objManual1.value.getXxrwScoreList=getXxrwScoreList.value
	submitList(objManual1.value).then((res) => {
		// console.log('保存',res)
       deptTreeList()
	});
	getXxrwScoreList.value.length = 0
	objManual1.value.getXxrwScoreList.length = 0
}
</script>
<style lang="scss" scoped>
    .scroll{
        overflow-y:scroll;
        overflow-x:hidden;
        height:100%
    }
    .line{
        border-top: 1px dashed #817B7B;
        margin: 0 auto;
        width: 1250px;
        height: 0;
    }
    .item {
        margin-bottom: 10px;
        /*margin-left: 10px;*/
        width: 350px;
    }
    .avue-crud__pagination{
        margin-left: 650px;
    }
</style>
